# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: leon

from coin.base.book import BookBuilderBase
from coin.exchange.quoinex_v2.kr_rest.product import QuoinexProduct


class BookEntry(object):
  def __init__(self, price, qty):
    self.price = float(price)
    self.qty = float(qty)


class BookBuilder(BookBuilderBase):
  ProductType = QuoinexProduct

  def __init__(self, native_symbol, book_builder_observer=None):
    super().__init__("Quoinex", native_symbol, book_builder_observer=book_builder_observer)

  def snapshot(self, bids: list, asks: list):
    if bids is not None:
      self._bid_price_map.clear()
      for price, qty in bids:
        price = float(price)
        qty = float(qty)
        self._insert_bid(price, qty, insert_only=True)
    if asks is not None:
      self._ask_price_map.clear()
      for price, qty in asks:
        price = float(price)
        qty = float(qty)
        self._insert_ask(price, qty, insert_only=True)

  def _insert_bid(self, price, qty, insert_only=False):
    assert price > 0
    assert qty > 0
    entry = BookEntry(price, qty)
    if insert_only:
      assert price not in self._bid_price_map
    self._bid_price_map[price] = entry

  def _insert_ask(self, price, qty, insert_only=False):
    assert price > 0
    assert qty > 0
    entry = BookEntry(price, qty)
    if insert_only:
      assert price not in self._ask_price_map
    self._ask_price_map[price] = entry

  def _delete_bid(self, price):
    del self._bid_price_map[price]

  def _delete_ask(self, price):
    del self._ask_price_map[price]

  def is_cross_book(self):
    try:
      bid0_price = self.bid0().price
      ask0_price = self.ask0().price
    except (AttributeError, IndexError):
      return False
    return bid0_price >= ask0_price
